package com.vanvalt.payhui.modules.pay.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.vanvalt.payhui.modules.pay.entity.BankCard;
import com.vanvalt.payhui.modules.pay.service.BankCardService;
import com.vanvalt.payhui.modules.pay.service.UserService;
import com.vanvalt.payhui.util.validate.IdcardValidator;

/**
 * @author Xiaoyang
 *
 */
@Controller
@RequestMapping(value = "${adminPath}/pay/bankcard")
public class BankCardController extends BaseController {

	@Autowired
	private BankCardService bankCardService;
	@Autowired
	private UserService userService;
	@Autowired
	private SystemService systemService;
	
	@ModelAttribute
	public BankCard get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return bankCardService.get(id);
		}else{
			return new BankCard();
		}
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(BankCard bankCard, HttpServletRequest request, HttpServletResponse response, Model model) {

		User user = UserUtils.getUser();
		
		List<String> roleIdList = user.getRoleIdList();
		for(String roleId:roleIdList){
			Role role = systemService.getRole(roleId);
			String dataScope = role.getDataScope();
			// 普通用户仅获取个人银行卡信息
			if(StringUtils.isNotBlank(dataScope) && "8".equals(dataScope)){ // 普通用户
				bankCard.setUserId(user.getId());
			}
		}
		
        Page<BankCard> page = bankCardService.findPage(new Page<BankCard>(request, response), bankCard); 
        model.addAttribute("page", page);
		return "modules/pay/bankCardList";
	}
	
	@RequestMapping(value = "form")
	public String form(BankCard bankCard, Model model) {
		
		// 当前登录用户
		User user = UserUtils.getUser();
		
		bankCard.setCreator(user);
		model.addAttribute("bankCard", bankCard);
		return "modules/pay/bankCardForm";
	}
	
	@RequestMapping(value = "save")
	public String save(BankCard bankCard, Model model, RedirectAttributes redirectAttributes) {
		
		if (!beanValidator(model, bankCard)){
			return form(bankCard, model);
		}
		
		String[] messages = this.getValidatorMessage(bankCard);
		
		if(messages.length > 0){
			
			addMessage(model, messages);
			return "modules/pay/bankCardForm";
		}
		
		if(bankCard.getId() == null || "".equals(bankCard.getId())){
			// 新增银行卡信息时，当前登录用户为持卡人
			User user = UserUtils.getUser();
			bankCard.setCreator(user);
			bankCard.setUserId(user.getId());
		}
		
		bankCardService.save(bankCard);
		
		addMessage(redirectAttributes, "保存银行卡信息'" + StringUtils.abbr(bankCard.getBankCardNum(),50) + "'成功");
		return "redirect:" + adminPath + "/pay/bankcard/?repage";
	}
	
	/**
	 * 信息校验
	 * @param bankCard
	 * @return
	 */
	private String[] getValidatorMessage(BankCard bankCard){
		
		String[] messages;
		
		List<String> msgList = Lists.newArrayList();
		// 持卡人姓名
		String cardName = bankCard.getCardName();
		if(StringUtils.isNotBlank(cardName)){
			
			//String nameReg = "^(([\u4e00-\u9fa5]{2,8})|([a-zA-Z]{2,16}))$";
			String nameReg = "^([\u4e00-\u9fa5]{2,8})$";
			if(!cardName.matches(nameReg)){
				msgList.add("持卡人姓名校验失败");
			}
		}
		
		// 证件号
		String idCard = bankCard.getIdCard();
		if(StringUtils.isNotBlank(idCard) && "01".equals(bankCard.getCertiType())){ // 证件类型为：身份证
			
			IdcardValidator iv = new IdcardValidator();
			if(!iv.isValidatedAllIdcard(idCard)){
				msgList.add("证件号校验失败");
			}
		}
		
		// 银行卡开户行
		String bankName = bankCard.getBankName();
		if(StringUtils.isNotBlank(bankName)){
			String nameReg = "^([\u4e00-\u9fa5]{2,12})$";
			if(!bankName.matches(nameReg)){
				msgList.add("银行卡开户行名称校验失败");
			}
		}
			
		// 银行卡账号
		String bankCardNum = bankCard.getBankCardNum();
		if(StringUtils.isNotBlank(bankCardNum)){
			
			String numReg = "^([0-9]*)$";
			if(!bankCardNum.matches(numReg)){
				msgList.add("银行卡账号校验失败");
			}
		}
		
		int size = msgList.size();
		messages = (String[]) msgList.toArray(new String[size]);
		
		return messages;
	}
	
	@RequestMapping(value = "delete")
	public String delete(BankCard bankCard, @RequestParam(required=false) Boolean isRe, RedirectAttributes redirectAttributes) {
		
		bankCardService.delete(bankCard);
		addMessage(redirectAttributes, (isRe!=null&&isRe?"发布":"删除")+"银行卡信息成功");
		return "redirect:" + adminPath + "/pay/bankcard/?repage";
	}
	
}
